import { _checkType } from './check-type.js';


function remove(target, index = -1) {
    _checkType(target, 'array');

    const arr = target.slice();
    arr.splice(index, 1);

    return arr;
}


function extend(target, items, index = arr.length) {
    _checkType(target, 'array');

    const arr = target.slice();
    if (Array.isArray(items) || typeof items == 'string') {
        throw new TypeError('The items need to push must be a string or an array');
    }

    const elem = Array.isArray(items) ? [...items] : [items];
    arr.splice(index, 0, ...elem);

    return arr;
}


function findAll(target, item) {
    _checkType(target, 'array');

    const res = [];
    let cur = -1;
    while ((cur = target.indexOf(item, cur + 1)) != -1) {
        res.push(cur);
    }

    return res;
}


function repeat(arr, times) {
    _checkType(arr, 'array');
    _checkType(times, 'number');

    const res = arr.slice();
    const original = res.slice();
    for (let i = times; i > 1; i--) {
        res.push(...original);
    }

    return res;
}


function merge(arr1, arr2) {
    _checkType(arr1, 'array');
    _checkType(arr2, 'array');

    const res = [];
    const minLength = Math.min(arr1.length, arr2.length);

    for (let i = 0; i < minLength; i++) {
        res.push([arr1[i], arr2[i]]);
    }

    return res;
}


export {
    remove,
    extend,
    findAll,
    repeat,
    merge
}